package com.example.birdfriends.utils.convert;

import cn.hutool.json.JSONArray;
import com.example.birdfriends.pojo.bird.Bird;
import com.example.birdfriends.pojo.bird.BirdAndAuthor;
import com.example.birdfriends.pojo.bird.BirdFront;
import com.example.birdfriends.pojo.bird.BirdsAndAuthors;
import com.example.birdfriends.pojo.comment.Comment;
import com.example.birdfriends.pojo.comment.CommentFront;
import com.example.birdfriends.pojo.comment.CommentsAndAuthors;
import com.example.birdfriends.pojo.follow.FollowFront;
import com.example.birdfriends.pojo.follow.Follower;
import com.example.birdfriends.pojo.message.Message;
import com.example.birdfriends.pojo.message.MessageVo;
import com.example.birdfriends.pojo.post.Post;
import com.example.birdfriends.pojo.post.PostAndAuthor;
import com.example.birdfriends.pojo.post.PostFront;
import com.example.birdfriends.pojo.post.PostsAndAuthors;
import com.example.birdfriends.pojo.user.User;
import com.example.birdfriends.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ConvertService {
    public List<MessageVo> messages2MessageVos(List<Message> messages, String curPage){
        List<MessageVo> messageVos = new ArrayList<>();
        for(Message message: messages){
            messageVos.add(message2MessageVo(message, curPage));
        }
        return messageVos;
    }

    public MessageVo message2MessageVo(Message message, String curPage){
        MessageVo messageVo = new MessageVo();
        messageVo.setMid(message.getMid());
        messageVo.setSenderId(message.getSenderId());
        messageVo.setReceiverId(message.getReceiverId());
        messageVo.setRead(message.getIsRead() == 1);
        Timestamp createAt = message.getCreateAt();
        if (Objects.equals(curPage, "friends")){  // 到年月日即可
            messageVo.setCreateAt(handleMsgInChat(createAt));
        }else if (curPage.equals("chat")){
            // 精确到小时分钟
            messageVo.setCreateAt(handleMsgInChat(createAt));
        }

        messageVo.setMsg(message.getMsg());

        return messageVo;
    }

    private final Timestamp curTime = new Timestamp(System.currentTimeMillis());  // 当前时间

    public String handleMsgInChat(Timestamp createAt){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(curTime.getTime());
        int curYear = calendar.get(Calendar.YEAR);
        int curDay = calendar.get(Calendar.DATE);

        calendar.setTimeInMillis(createAt.getTime());
        int createYear = calendar.get(Calendar.YEAR);
        int createDay = calendar.get(Calendar.DATE);

        String[] timeArr = createAt.toString().split(" ")[1].split(":");
        if(createYear < curYear){
            return createAt.toString().split(" ")[0]+" "+timeArr[0]+":"+timeArr[1];
        }
        int differHour = differHour(createAt, curTime);
        if (curDay != createDay){  // 日期不同，显示月日时分
            String[] dateArr = createAt.toString().split(" ")[0].split("-");
            return dateArr[1]+"-"+dateArr[2]+" "+timeArr[0]+":"+timeArr[1];
        }else {  // 日期相同，二者时间差不会超过24h
            if(differHour <= 0){
                int minute = differMinute(createAt, curTime);
                if(minute <= 0){
                    return "刚刚";
                }
                return minute+"分钟前";
            }
            else if (differHour < 12){
                // 未达到12小时，显示 小时分钟
                return differHour+"小时前";
            } else{
//                String[] dateArr = createAt.toString().split(" ")[0].split("-");
                return timeArr[0]+":"+timeArr[1];
            }
        }
    }

    public String handleMessageTimeInFriends(Timestamp createAt){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(curTime.getTime());
        int curYear = calendar.get(Calendar.YEAR);

        calendar.setTimeInMillis(createAt.getTime());
        int createYear = calendar.get(Calendar.YEAR);

        if(createYear < curYear){
            return createAt.toString().split(" ")[0];
        }
        int differHour = differHour(createAt, curTime);
        if (differHour > 24){
            // 超过24小时，显示月日
            String[] timeArr = createAt.toString().split(" ");
            String[] dateArr = timeArr[0].split("-");
            return dateArr[1]+"-"+dateArr[2];
        }else
            return differHour+"小时前";
    }

    private int differHour(Timestamp startTime, Timestamp endTime){
        long dayM = 1000*24*60*60;
        long hourM = 1000*60*60;
        long minute = 1000*60;
        long differ = endTime.getTime() - startTime.getTime();
        long hour = differ % dayM / hourM + 24 * (differ / dayM);
        return Integer.parseInt(String.valueOf(hour));
    }

    private int differMinute(Timestamp start, Timestamp end){
        long differ = end.getTime() - start.getTime();
        long minute = differ / 1000 / 60;
        return Integer.parseInt(String.valueOf(minute));
    }
    public BirdAndAuthor findBirdAndAuthor(Bird bird){
        Long authorId = bird.getAuthorId();
        User author = userService.findUserByUid(authorId);
        BirdAndAuthor birdAndAuthor = new BirdAndAuthor();
        birdAndAuthor.setAuthor(author);
        birdAndAuthor.setBird(bird2BirdFront(bird));
        return birdAndAuthor;
    }

    public BirdsAndAuthors findBirdsAndAuthors(List<BirdFront> birdFronts){
        List<User> authors = new ArrayList<>();
        for(BirdFront birdFront: birdFronts){
            Long authorId = birdFront.getAuthorId();
            User author = userService.findUserByUid(authorId);
            author.setPassword("");
            authors.add(author);
        }

        BirdsAndAuthors birdsAndAuthors = new BirdsAndAuthors();
        birdsAndAuthors.setAuthors(authors);
        birdsAndAuthors.setBirds(birdFronts);

        return birdsAndAuthors;
    }

    public List<BirdFront> birds2BirdFronts(List<Bird> birds){
        List<BirdFront> birdFronts = new ArrayList<>();
        for(Bird bird: birds){
            BirdFront birdFront = bird2BirdFront(bird);
            birdFronts.add(birdFront);
        }

        return birdFronts;
    }

    public BirdFront bird2BirdFront(Bird bird){
        BirdFront birdFront = new BirdFront();
        birdFront.setBid(bird.getBid());
        birdFront.setBirdname(bird.getBirdname());
        birdFront.setIntroduction(bird.getIntroduction());
        birdFront.setSection(bird.getSection());
        birdFront.setImages(string2List(bird.getImages()));
        birdFront.setAuthorId(bird.getAuthorId());
        if(bird.getCreateAt() != null) birdFront.setCreateAt(timestamp2YMD(bird.getCreateAt()));
        return birdFront;
    }

    public Bird birdFront2Bird(BirdFront birdFront){
        Bird bird = new Bird();
        bird.setBid(birdFront.getBid());
        bird.setBirdname(birdFront.getBirdname());
        bird.setSection(birdFront.getSection());
        bird.setIntroduction(birdFront.getIntroduction());
        if (birdFront.getImages() != null) bird.setImages(list2String(birdFront.getImages()));
        bird.setAuthorId(birdFront.getAuthorId());
        if(birdFront.getCreateAt() != null) bird.setCreateAt(ymd2Timestamp(birdFront.getCreateAt()));
        return bird;
    }

    public FollowFront follow2FollowFront(Follower follow, boolean addSuccess) {
        FollowFront followFront = new FollowFront();
        followFront.setFid(follow.getFid());
        followFront.setCurrentUid(follow.getFollowUid());
        followFront.setFollowedUid(follow.getFollowedId());
        followFront.setFollow(addSuccess);
        return followFront;
    }

    public Post postFront2Post(PostFront postFront) throws ParseException {
        Post post = new Post();
        post.setPid(postFront.getPid());
        post.setVideos(list2String(postFront.getVideos()));
        post.setImages(list2String(postFront.getImages()));
        post.setContent(postFront.getContent());
        post.setTitle(postFront.getTitle());
        post.setTheme(postFront.getTheme());
        post.setCreateAt(ymd2Timestamp(postFront.getCreateAt()));
        post.setUid(postFront.getAuthorId());

        return post;
    }

    public String timestamp2YMD(Timestamp time){
        Date date = Date.from(time.toInstant());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    public Timestamp ymd2Timestamp(String dateString) {
        return Timestamp.valueOf(dateString);
    }

    @Autowired
    private CommentService commentService = null;

    public PostFront post2PostFront(Post post, Long curLoginUid, String curPage){
        PostFront front = new PostFront();
        Long pid = post.getPid();  // 当前帖子的id
        front.setPid(pid);
        front.setTitle(post.getTitle());
        front.setTheme(post.getTheme());
        front.setContent(post.getContent());
        front.setCreateAt(timestamp2YMD(post.getCreateAt()));  // 将post的Date格式转化成字符串
//            System.out.println("检查图片："+posts.get(i).getImages());
        front.setImages(string2List(post.getImages()));
//            System.out.println("查看转化结果："+front.getImages());
        front.setPreviewImages(string2List(post.getImages()));
        front.setVideos(string2List(post.getVideos()));
        List<Long> praiseIds = praiseService.findPraisesByPid(pid);
        Long likes = (long)praiseIds.size();  // 当前帖子的点赞个数
        front.setLikes(likes);
        // 检查当前登录的用户是否点赞了当前帖子，设置相关的likeIcon和active
//        System.out.println("当前登录的用户："+curLoginUid+"；当前遍历到的帖子id："+pid);
        if(curLoginUid != null && !praiseService.findPraisesByPidAndUid(pid, curLoginUid).isEmpty()) {
            front.setLikeIcon("http://localhost:8888/icons/like_active.png");
            front.setActive(true);
        }else {  // 当前登录的用户没有对该帖子进行点赞
            front.setLikeIcon("http://localhost:8888/icons/like_no_active.png");
            front.setActive(false);
        }

        // 查询当前帖子的读者数量
        Long readers = (long)removeDuplicateUid(pid).size();
        front.setReaders(readers);

        // 当前帖子的评论数
        Long comments = (long) commentService.findCommentsByPid(pid).size();  // 当前帖子的所有评论
        front.setComments(comments);

        front.setAuthorId(post.getUid());
        front.setCurLoginUid(curLoginUid);
        front.setCurPage(curPage);

        return front;
    }

    public PostAndAuthor findPostAuthor(Post post, Long curLoginUid, String curPage){
        PostFront postFront = post2PostFront(post, curLoginUid, curPage);
        Long authorId = postFront.getAuthorId();
        User author = userService.findUserByUid(authorId);
        author.setPassword("");
        PostAndAuthor postAndAuthor = new PostAndAuthor();
        postAndAuthor.setPost(postFront);
        postAndAuthor.setPostAuthor(author);

        return postAndAuthor;
    }

    public PostsAndAuthors findPostsAuthors(List<Post> posts, Long curLoginUid, String curPage){
        // 查找每个帖子的作者
        List<PostFront> postFronts = posts2PostFronts(posts, curLoginUid, curPage);
        List<User> users = new ArrayList<>();
        for(PostFront postFront: postFronts){
            Long uid = postFront.getAuthorId();
            User user = userService.findUserByUid(uid);
            user.setPassword("");
            users.add(user);
        }
        PostsAndAuthors postsAndAuthors = new PostsAndAuthors();
        postsAndAuthors.setPostAuthorList(users);
        postsAndAuthors.setPostList(postFronts);
        return postsAndAuthors;
    }

    public PostsAndAuthors findAuthors(List<PostFront> posts){
        // 查找每个帖子的作者
        List<User> authors = new ArrayList<>();
        for(PostFront postFront: posts){
            Long uid = postFront.getAuthorId();
            User user = userService.findUserByUid(uid);
            user.setPassword("");
            authors.add(user);
        }
        PostsAndAuthors postsAndAuthors = new PostsAndAuthors();
        postsAndAuthors.setPostAuthorList(authors);
        postsAndAuthors.setPostList(posts);
        return postsAndAuthors;
    }

    public List<Long> removeDuplicateUid(Long pid){
        List<Long> rids = readService.findReadersByPid(pid);  // 通过当前帖子id查找当前帖子的所有阅读id
        // 遍历阅读id，利用每个阅读id去查找对用的用户id（排除多个用户）
        List<Long> uids = new ArrayList<>();
        for(Long rid: rids){
            Long uid = readService.findReadUidByRid(rid);  // 根据阅读id查找对应的用户id
            uids.add(uid);
        }
        List<Long> newUids = new ArrayList<>();
        for(Long uid: uids){
            if (!newUids.contains(uid)){
                newUids.add(uid);
            }
        }

        return newUids;
    }

    @Autowired
    PraiseService praiseService = null;
    @Autowired
    ReadService readService = null;

    public CommentFront comment2CommentFront(Comment comment){
        CommentFront commentFront = new CommentFront();
        commentFront.setCid(comment.getCid());
        commentFront.setContent(comment.getContent());
        commentFront.setCreateAt(timestamp2YMD(comment.getCreateAt()));
        commentFront.setUid(comment.getUid());
        commentFront.setPid(comment.getPid());

        return commentFront;
    }

    @Autowired
    private UserService userService = null;

    public CommentsAndAuthors comments2CommentsAndAuthors(List<Comment> comments){
        CommentsAndAuthors commentsAndAuthors = new CommentsAndAuthors();

        List<User> authors = new ArrayList<>();
        List<CommentFront> commentFronts = new ArrayList<>();
        for(Comment comment: comments){
            Long uid = comment.getUid();
            User author = userService.findUserByUid(uid);
            commentFronts.add(comment2CommentFront(comment));
            authors.add(author);
        }
        commentsAndAuthors.setAuthorList(authors);
        commentsAndAuthors.setCommentList(commentFronts);

        return commentsAndAuthors;
    }

    public List<PostFront> posts2PostFronts(List<Post> posts, Long curLoginUid, String curPage){
//        List<Post> posts = postService.findPostsByUid(uid);  // 当前用户的所有帖子
        List<PostFront> postFrontList = new ArrayList<>();
        for(Post post: posts){
            PostFront postFront1 = post2PostFront(post, curLoginUid, curPage);  // 转化成了postFront
            postFrontList.add(postFront1);
        }

        return postFrontList;
    }

    public <E> String list2String(List<E> list){
        JSONArray jsonArray = new JSONArray();
        for(int i = 0; i < list.size(); i++){
            try {
                jsonArray.put(list.get(i));
            }catch (Exception e){
                e.printStackTrace();
                break;
            }
        }

        return jsonArray.toString();
    }

    public List<String> string2List(String s){
        List<String> list = new ArrayList<>();
        try{
            JSONArray jsonArray = new JSONArray(s);
            for (Object o : jsonArray) {
                list.add(o.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
}
